package asynctimer

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"time"
	"uwbwebapp/pkg/biz"
	"uwbwebapp/pkg/cache"
	"uwbwebapp/pkg/tools"
)

func writeToFile(date time.Time) {
	sDate := date.Format(tools.GOOGLE_DATETIME_FORMAT_NO_TIME)
	rkey := fmt.Sprintf("UWB_record_*_%s", sDate)
	rctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	rkeys, err := cache.RedisDatabase.Keys(rctx, rkey).Result()
	cancel()
	if err == nil {
		for _, key := range rkeys {
			swimmerId := strings.Split(key, "_")[2]
			filePath := fmt.Sprintf("./uwbrecords/%s/%s", sDate, swimmerId)
			tools.CheckAndMakeFileFullPath(filePath)
			f, fe := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
			if fe == nil {
				records, _ := biz.GetUWBTerminalSingleDateRecordsFromRedis(swimmerId, date)
				byteRecords, jsonErr := json.Marshal(records)
				if jsonErr == nil {
					_, writeErr := f.WriteString(string(byteRecords)) // 写入到文件
					if writeErr != nil {
						fmt.Println(writeErr.Error())
					}
				}
			} else {
				fmt.Println(fe.Error())
			}
			fe = f.Close()
			if fe != nil {
				fmt.Println(fe.Error())
			}
			// 这里需要调用删除该KEY
			rctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
			_, err = cache.RedisDatabase.Del(rctx, key).Result()
			if err != nil {
				fmt.Println(err.Error())
			}
			cancel()
		}
	}
}

func UWBTerminalRecordsToFile() {
	for {
		now := time.Now()
		if now.Format(tools.GOOGLE_DATETIME_FORMAT_NO_DATE_NO_NANO) == "23:59:59" {
			time.Sleep(5 * time.Second)
			fmt.Println("开始将今日的 UWB Record 记录缓存写入到记录文件。")
			writeToFile(now)
			fmt.Println("写入完成。")
		}
		time.Sleep(100 * time.Millisecond)
	}
}
